package com.moonLight.weblog.admin.service.Impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.moonLight.weblog.admin.convert.CommentConvert;
import com.moonLight.weblog.admin.event.UpdateCommentEvent;
import com.moonLight.weblog.admin.model.vo.comment.DeleteCommentReqVO;
import com.moonLight.weblog.admin.model.vo.comment.ExamineCommentReqVO;
import com.moonLight.weblog.admin.model.vo.comment.FindCommentPageListReqVO;
import com.moonLight.weblog.admin.model.vo.comment.FindCommentPageListRspVO;
import com.moonLight.weblog.admin.service.AdminCommentService;
import com.moonLight.weblog.common.domain.dos.CommentDO;
import com.moonLight.weblog.common.domain.mapper.CommentMapper;
import com.moonLight.weblog.common.enums.CommentStatusEnum;
import com.moonLight.weblog.common.enums.ResponseCodeEnum;
import com.moonLight.weblog.common.exception.BizException;
import com.moonLight.weblog.common.utils.Response;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.index.qual.SameLen;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Slf4j
public class AdminCommentServiceImpl implements AdminCommentService {
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    @Override
    public Response findCommentPageList(FindCommentPageListReqVO findCommentPageListReqVO) {

        Long current = findCommentPageListReqVO.getCurrent();
        Long size = findCommentPageListReqVO.getSize();

        Integer status = findCommentPageListReqVO.getStatus();
        String routerUrl = findCommentPageListReqVO.getRouterUrl();
        LocalDate startDate = findCommentPageListReqVO.getStartDate();
        LocalDate endDate = findCommentPageListReqVO.getEndDate();

        Page<CommentDO> commentDOPage = commentMapper.selectPageList(current, size, routerUrl, startDate, endDate, status);
        List<CommentDO> records = commentDOPage.getRecords();
        List<FindCommentPageListRspVO> vos = null;
        if (!CollectionUtils.isEmpty(records)){
            vos = records.stream().map(commentDO -> CommentConvert.INSTANCE.convertDO2VO(commentDO)).collect(Collectors.toList());
        }
        return Response.success(vos);
    }

    @Override
    public Response deleteComment(DeleteCommentReqVO deleteCommentReqVO) {

        //需要删除的评论ID
        Long commentId = deleteCommentReqVO.getId();
        //查到需要删除的评论
        CommentDO commentDO = commentMapper.selectById(commentId);

        if (Objects.isNull(commentDO)){
            log.warn("需要删除的评论{}不存在",commentId);
            throw new BizException(ResponseCodeEnum.COMMENT_NOT_FOUND);
        }

        //根据id删除评论
        commentMapper.deleteById(commentId);
        //判断被删除评论级别
        Long replyCommentId = commentDO.getReplyCommentId();
        if (Objects.isNull(replyCommentId)){
            //一级评论 直接删除该评论下的所有评论内容 =>  删除父ID是该评论ID的评论
            commentMapper.deleteByParentCommentId(commentId);
        }else{
            //二级评论 删除此评论下的所有回复评论
            deleteAllChildComment(commentId);
        }
        return Response.success();
    }

    @Override
    public Response examine(ExamineCommentReqVO examineCommentReqVO) {
        Long commentId = examineCommentReqVO.getId();
        CommentDO commentDO = commentMapper.selectById(commentId);

        if (Objects.isNull(commentDO)){
            log.warn("需要审核的评论{}不存在",commentId);
            throw new BizException(ResponseCodeEnum.COMMENT_NOT_FOUND);
        }

        //处于待审核的评论才能审核
        if (!Objects.equals(commentDO.getStatus(), CommentStatusEnum.WAIT_EXAMINE.getCode())){
            log.warn("评论{}状态不是待审核状态，不能审核",commentId);
            throw new BizException(ResponseCodeEnum.COMMENT_STATUS_NOT_WAIT_EXAMINE);
        }
        //更新评论status
        commentMapper.updateById(CommentDO.builder()
                        .id(commentId)
                        .status(examineCommentReqVO.getStatus())
                        .reason(examineCommentReqVO.getReason())
                        .updateTime(LocalDateTime.now())
                .build());
        //执行发送邮件的事件
        log.info("评论审核完成，发送邮件通知用户");
        applicationEventPublisher.publishEvent(new UpdateCommentEvent(this,commentId));
        return Response.success();
    }

    /**
     * 删除该评论下的所有评论
     * @param commentId
     */
    private void deleteAllChildComment(Long commentId) {
        // 查询此评论的所有回复
        List<CommentDO> childCommentDOS = commentMapper.selectAllByReplyCommentIdCommentDos(commentId);

        if (CollectionUtils.isEmpty(childCommentDOS))
            return;

        // 循环递归删除
        childCommentDOS.forEach(childCommentDO -> {
            Long childCommentId = childCommentDO.getId();

            commentMapper.deleteById(childCommentId);
            // 递归调用
            deleteAllChildComment(childCommentId);
        });

    }

}
